<template>
  <div class="region" @click="closePopover">
    <!-- <iframe src="http://localhost:8080/region/regionPage" frameborder="0" style="height: 100%;width: 100%;" /> -->
    <el-row style="height: 100%">
      <el-col :span="6" class="left">
        <pageCard :title-name="'区域树'" :type="'pageTitle'">
          <el-input v-model="filterText" placeholder="输入关键字进行过滤" style="padding-bottom: 10px" />
          <el-scrollbar style="height: calc(100% - 42px)" class="treeContent">
            <el-tree
              ref="tree"
              :data="regionTree"
              default-expand-all
              node-key="id"
              highlight-current
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              :props="defaultProps"
              @node-click="nodeClick"
            >
              <span
                slot-scope="{ node, data }"
                class="treeRow"
                @mouseenter="mouseenter(data)"
                @mouseleave="mouseleave(data)"
              >
                <i class="el-icon-office-building" />
                <span style="padding-left: 5px">{{ node.label }}</span>
                <el-popover
                  id="popoverDiv"
                  v-model="data.popoverShow"
                  placement="right"
                  width="200"
                  trigger="manual"
                  popper-class="regionPopover"
                >
                  <ul v-show="popoverType === 'index'" class="popoverUl">
                    <li v-permission="['system:region:add']" class="popoverItem" @click="clickAddDept(data)">
                      添加子区域
                    </li>
                    <li
                      v-show="!data.company"
                      v-permission="['system:region:del']"
                      class="popoverItem"
                      style="color: red"
                      @click="clickDeleteDept(data)"
                    >
                      删除
                    </li>
                  </ul>
                  <svg-icon
                    v-show="data.show"
                    slot="reference"
                    icon-class="treeUnfold"
                    class="iconTreeUnfold"
                    @click="setPopoverShowTrue(data)"
                  />
                </el-popover>
              </span>
            </el-tree>
          </el-scrollbar>
        </pageCard>
      </el-col>
      <el-col :span="18" style="height: 100%">
        <pageCard :title-name="'区域信息'" style="height: 100%" :type="'pageTitle'">
          <div style="padding-left: 20px">
            <el-button
              v-show="pageType === 'index' && pageData.regionId !== null"
              v-permission="['system:region:edit']"
              type="primary"
              class="headerBtn"
              @click="editRegion"
            >
              编 辑
            </el-button>
            <el-button v-show="pageType !== 'index'" type="primary" class="headerBtn" @click="submitForm">
              保 存
            </el-button>
            <el-button v-show="pageType !== 'index'" plain class="topBtn" @click="closeEdit">取 消</el-button>
            <el-form
              v-show="pageType !== 'index'"
              ref="formData"
              :model="formData"
              :rules="rules"
              label-width="100px"
              class="formDiv"
            >
              <el-form-item label="区域名称" prop="regionName">
                <el-input v-model="formData.regionName" maxlength="20" show-word-limit class="show-word-limit" />
              </el-form-item>
              <el-form-item label="区域描述">
                <el-input
                  v-model="formData.regionDescribe"
                  type="textarea"
                  maxlength="50"
                  show-word-limit
                  class="show-word-limit"
                  :autosize="{ minRows: 2 }"
                />
              </el-form-item>
              <el-form-item label="区域负责人">
                <el-input
                  v-model="formData.user.value"
                  suffix-icon="el-icon-arrow-down"
                  class="inputSelect"
                  :readonly="true"
                  @focus="clickSingleChoose()"
                />
              </el-form-item>
              <el-form-item label="联系电话">
                <el-input v-model="formData.mobileTel" :readonly="true" />
              </el-form-item>
            </el-form>
            <el-form
              v-show="pageType === 'index' && pageData.regionId !== null"
              label-width="100px"
              class="formDiv"
            >
              <el-form-item label="区域名称：">
                <div class="formText">{{ pageData.regionName }}</div>
              </el-form-item>
              <el-form-item label="区域描述：">
                <div class="formText">{{ pageData.regionDescribe }}</div>
              </el-form-item>
              <el-form-item label="区域负责人：">
                <div class="formText" @focus="clickSingleChoose()">{{ pageData.user.value }}</div>
              </el-form-item>
              <el-form-item label="联系电话：">
                <div class="formText">{{ pageData.mobileTel }}</div>
              </el-form-item>
            </el-form>
            <div v-show="pageData.regionId === null" class="notDataText">请选择区域</div>
          </div>
        </pageCard>
      </el-col>
    </el-row>
    <peopleSingleChoose v-if="peopleSingleChooseIndex" ref="peopleSingleChoose" @submit="submitPeople" />
  </div>
</template>

<script>
import peopleSingleChoose from '@/components/dialogChoose/peopleSingleChoose'
import pageCard from '@/components/page/pageCard'
import { getRegionTree, getRegionInfo, addRegion, editRegion, deleteRegion } from '@/api/system-management'
export default {
  name: 'Region',
  components: {
    pageCard,
    peopleSingleChoose
  },
  data() {
    return {
      pageType: 'index',
      peopleSingleChooseIndex: false,
      // 表单data
      formData: {
        regionId: null,
        regionName: '',
        regionDescribe: '',
        user: {
          id: null,
          value: ''
        },
        mobileTel: null
      },
      pageData: {
        regionId: null,
        regionName: '',
        regionDescribe: '',
        user: {
          id: null,
          value: ''
        },
        mobileTel: null
      },
      rules: {
        regionName: [{ required: true, message: '请输入区域名称', trigger: 'blur' }]
      },
      // 树data
      filterText: '',
      regionTree: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      popoverNode: {},
      popoverType: 'index',
      editDeptName: '',
      addNode: null,
      addDeptName: ''
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.getRegionTree()
  },
  methods: {
    // 编辑表单函数
    editRegion() {
      this.pageType = 'edit'
      this.formData = JSON.parse(JSON.stringify(this.pageData))
    },
    // 提交表单函数
    submitForm() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          if (this.pageType === 'add') {
            addRegion(this.formData).then((res) => {
              this.$notify({
                title: '成功',
                message: '添加区域成功',
                type: 'success'
              })
              this.getRegionTree()
              this.getRegionInfo(res.data)
              this.pageType = 'index'
            })
          } else {
            editRegion(this.formData).then((res) => {
              this.$notify({
                title: '成功',
                message: '修改区域成功',
                type: 'success'
              })
              this.getRegionTree()
              this.getRegionInfo(this.formData.regionId)
              this.pageType = 'index'
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 点击添加区域
    clickAddDept(node) {
      this.cleanForm()
      this.addNode = node
      this.pageType = 'add'
      if (node.company) {
        this.formData.regionId = null
      } else {
        this.formData.regionId = node.id
      }
      this.closePopover()
    },
    // 点击取消
    closeEdit() {
      this.pageType = 'index'
      this.cleanPage()
      this.cleanForm()
    },
    // 清空form
    cleanForm() {
      this.formData = {
        regionId: null,
        regionName: '',
        regionDescribe: '',
        user: {
          id: null,
          value: ''
        },
        mobileTel: null
      }
    },
    // 清空page
    cleanPage() {
      this.pageData = {
        regionId: null,
        regionName: '',
        regionDescribe: '',
        user: {
          id: null,
          value: ''
        },
        mobileTel: null
      }
    },
    // 单用户选择弹窗
    clickSingleChoose() {
      this.peopleSingleChooseIndex = true
      this.$nextTick(() => {
        this.$refs.peopleSingleChoose.is(1, '选择区域负责人')
      })
    },
    // 用户提交函数
    submitPeople(indexx, rowData, rowAllData) {
      this.formData.user = rowData
      this.formData.mobileTel = rowAllData.mobileTel
    },
    // 获取区域树
    getRegionTree() {
      this.regionTree = []
      getRegionTree().then((res) => {
        this.regionTree.push(res.data)
      })
    },
    // 获取区域信息
    getRegionInfo(id) {
      getRegionInfo({ regionId: id }).then((res) => {
        this.pageData = res.data
      })
    },
    // 点击删除区域
    clickDeleteDept(node) {
      this.$confirm('此操作将永久删除"' + node.label + '"与其子区域, 是否确定要删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteRegion({ regionId: node.id }).then((res) => {
            this.$notify({
              title: '成功',
              message: '删除区域成功',
              type: 'success'
            })
            this.cleanPage()
            this.setPopoverShowFalse(this.regionTree)
            this.getRegionTree()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 以下树函数
    // 过滤树函数
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 以下函数都是和popover有关的函数
    setInitTreeData() {
      for (const item of this.regionTree) {
        item['popoverShow'] = false
        item['show'] = false
        if (item.children) {
          this.setPopoverShowFalse(item.children)
        }
      }
    },
    // 鼠标悬浮进tree
    mouseenter(data) {
      this.$set(data, 'show', true)
    },
    // 鼠标悬浮出tree
    mouseleave(data) {
      if (this.popoverNode !== {} && this.popoverNode.id === data.id) {
        this.$set(data, 'show', true)
      } else {
        this.$set(data, 'show', false)
      }
    },
    // 点击节点
    async nodeClick(node) {
      await this.setPopoverShowFalse(this.regionTree)
      if (!node.company) {
        this.getRegionInfo(node.id)
      }
      // eslint-disable-next-line require-atomic-updates
      node.show = true
      this.pageType = 'index'
      this.popoverNode = {}
    },
    // 点击popover区域以外关闭popover
    closePopover() {
      var sp = document.getElementById('popoverDiv')
      if (sp) {
        if (!sp.contains(event.target)) {
          // 这句是说如果我们点击到了id为popoverDiv以外的区域
          this.setPopoverShowFalse(this.regionTree)
          this.popoverNode = {}
        }
      }
    },
    // 让区域树有各种show属性
    // 使节点popoverShow为true
    setPopoverShowTrue(data) {
      const test = JSON.parse(JSON.stringify(data))
      setTimeout(() => {
        data.popoverShow = !test.popoverShow
        this.popoverNode = data
        this.$set(data, 'show', true)
      }, 100)
    },
    // 使节点popoverShow为false
    setPopoverShowFalse(treeData) {
      for (const item of treeData) {
        item.popoverShow = false
        this.$set(item, 'show', false)
        if (item.children) {
          this.setPopoverShowFalse(item.children)
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
.regionPopover {
  padding: 0px;
  .popoverUl {
    margin: 0;
    padding: 0px;
    .popoverItem {
      list-style-type: none !important;
      padding: 0 15px;
      cursor: pointer;
      line-height: 40px;
    }
    .popoverItem:hover {
      background-color: #f0f7ff;
    }
  }
}
.region {
  height: 99%;
  .left {
    height: 100%;
    /deep/.el-scrollbar__view {
      height: 100%;
    }
    .treeContent {
      /deep/.el-scrollbar__view {
        height: auto;
      }
    }
  }
  .headerBtn {
    margin-left: 10px;
    margin-right: 10px;
    padding: 8px 17px;
  }
  .inputSelect {
    /deep/ .el-input__icon {
      cursor: pointer;
    }
  }
  .formDiv {
    width: 40%;
    padding-top: 40px;
  }
  // .formText{
  //   font-size: 17px;
  // }
  .notDataText {
    padding: 20px;
    color: gray;
  }
  /deep/ .el-form-item {
    margin-bottom: 50px;
    label {
      font-weight: 500;
      // font-size: 17px;
    }
  }
  /deep/.el-tree {
    border-right: none;
    .treeRow {
      width: 100%;
      display: flex;
      align-items: center;
    }
    .el-tree-node__expand-icon {
      font-size: 18px;
      position: relative;
      left: 5px;
    }

    .el-tree-node .is-current {
      background-color: #f5f7fa;
    }
    .el-tree-node__expand-icon {
      float: right;
      // margin-right: 1.5625rem !important;
    }
    .el-tree-node__content {
      height: 2.5rem;
      line-height: 2.5rem;
      font-size: 16px;
    }
    .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
      background: #ecf5ff;
    }
    .iconTreeUnfold {
      font-size: 14px;
      display: flex;
      align-items: center;
    }
  }
}
</style>
